package com.lmx.persistence.service;

import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.collect.Maps;
import com.lmx.common.constants.CommonConstants;
import com.lmx.common.constants.LeaveStatus;
import com.lmx.common.util.CommonUtil;
import com.lmx.persistence.service.common.BaseCrudServiceImpl;
import com.lmx.repoDomain.exception.BusinessException;
import com.lmx.repoDomain.tmodel.Customer;
import com.lmx.repoDomain.tmodel.CustomerLeave;

/**
 * 老人离职service
 *
 * @author ytche
 * @date 2017年6月20日
 *
 */
@Service(value = "customerLeaveService")
public class CustomerLeaveServiceImpl extends BaseCrudServiceImpl<CustomerLeave> implements
		CustomerLeaveService {
	private Log logger = LogFactory.getLog(this.getClass());
	@Autowired
	private CustomerEventService eventService;

	@Override
	public CustomerLeave create(CustomerLeave entity) {
		if (checkCustomerInLeaving(entity.getCustomer())) {
			throw new BusinessException("",
					CommonConstants.LEAVA_ERROR_CODE.CUSTOMER_IN_LEAVING.lable(), null);
		}
		Integer todayBegin = CommonUtil.getDayBegin();
		entity.setStatus(todayBegin >= entity.getStartTime() ? LeaveStatus.LEAVING.getValue()
				: LeaveStatus.LEAVE_ALLOWED.getValue());
		entity.setCloseStatus(CommonConstants.DEFAULT_STATUS_NO_0);
		return super.create(entity);
	}

	@Override
	@Transactional
	public CustomerLeave update(CustomerLeave entity) {
		CustomerLeave oldEntity = super.findOne(entity.getId());
		if (!oldEntity.getCustomer().getId().equals(entity.getCustomer().getId())
				&& checkCustomerInLeaving(entity.getCustomer())) {
			throw new BusinessException("",
					CommonConstants.LEAVA_ERROR_CODE.CUSTOMER_IN_LEAVING.lable(), null);
		}
		if (oldEntity.getCloseStatus() == CommonConstants.DEFAULT_STATUS_YES_1) {
			throw new BusinessException(null,
					CommonConstants.LEAVA_ERROR_CODE.LEAVE_CLEARED.lable(), "");
		}
		if (LeaveStatus.LEAVE_COMPLETE.getValue().equals(entity.getStatus())) {
			this.eventService.sysLeaveEvent(entity, null);
		}
		return super.update(entity);
	}

	@Override
	public boolean sysLeaveStatus() {
		List<CustomerLeave> rowData = super.findNotDelete("status",
				LeaveStatus.LEAVE_ALLOWED.getValue());
		for (CustomerLeave customerLeave : rowData) {
			Integer today = CommonUtil.getDayBegin();
			Integer startTime = CommonUtil.getDayBegin(customerLeave.getStartTime());
			if (today >= startTime) {
				customerLeave.setStatus(LeaveStatus.LEAVING.getValue());
				super.update(customerLeave);
				eventService.sysLeaveEvent(customerLeave, today);
			}
		}
		return true;
	}

	@Override
	public Boolean updateCloseStatus(Long... ids) {
		List<CustomerLeave> list = super.findByIds(ids);
		if (list == null || list.size() < 1) {
			this.logger.error("老人请假,更新状态的数据不存在");
			return false;
		}
		list.forEach(p -> {
			p.setCloseStatus(CommonConstants.DEFAULT_STATUS_YES_1);
			super.update(p);
		});
		return true;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Boolean checkCustomerInLeaving(Customer customer) {
		String queryStr = "from CustomerLeave where customer.id=:customerId and delStatus= 0 and endTime is null ";
		List<CustomerLeave> list = super.em.createQuery(queryStr)
				.setParameter("customerId", customer.getId()).getResultList();
		return list != null && list.size() > 0;
	}

	@Override
	public Integer getLeaveStatus(Customer customer) {
		Map<String, Object> params = Maps.newHashMap();
		params.put("customer.id", customer.getId());
		params.put("status", LeaveStatus.LEAVING.getValue());
		params.put("delStatus", CommonConstants.DEL_STATUS_NO_0);
		List<CustomerLeave> leaves = super.find(params);
		return leaves != null && leaves.size() > 0 ? CommonConstants.DEFAULT_STATUS_YES_1
				: CommonConstants.DEFAULT_STATUS_NO_0;
	}
}
